import { ref, reactive, onMounted, } from "vue";
import { useRoute } from "vue-router";
import { type PaginationProps } from "@pureadmin/table";
import qs from "qs";
import { ElMessage } from "element-plus";
import {
  GetProjectProposalNames,
  GetProductTerm,
  GetInfoByAssetTransferId,
  GetExcessCollateral,
  AssetTransferGetSmallLoanCreditbalance,
  GetSPVName,
  GetPriorityHierarchy,
  SecurityCreditRatingCreate,
  SecurityCreditRatingGetAll,
  PredeterminedRating,
  GetSettlementTime,
} from "@/api/stu/SupplyChainFinance";
import { nextTick } from "process";
export function usePortrait() {
  const route = useRoute()
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "项目名称",
      prop: "assetSecuritizationName",
      minWidth: 100
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];
  const newReportVisible = ref(false)
  const filterAssetTransferId = ref()
  const filterDataList = ref([])
  const showReport = ref<boolean>(false);
  const caseDialog = ref<boolean>(false);
  const tableData = ref([])
  const caseList = ref([])
  const resultStr = ref('')
  const filterSelectId = ref('')
  const createData = reactive({
    assetSecuritizationName: '',
    assetPoolId: "",
    creditEnhancementRanking: "",
    issuancePercentage: '',
    individualIssue: '',
    issuanceAmount: '',//总发行金额 
    initialStartDate: "",//项目的初始起始日期 
    legalFinalMaturityDate: "",// 项目的法定最终到期日期 
    pooledCapitalBy: "",//资本贡献方的名称（例如，XXX 公司） 
    principalBalance: '',// 资产池的本金余额 
    initiator: "",// 发起/服务机构：发起人名称。 
    trusteeSpv: "",/// 受托机构：SPv企业资产证券化）
    interestRate: ''/// 发行利率 
  })
  const detailData = ref()
  onMounted(async () => {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    const res = await GetProjectProposalNames(data)
    if (res.success) {
      filterDataList.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
    getReport()
  })
  async function getReport() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
    };
    let res = await SecurityCreditRatingGetAll(data)
    if (res.success) {
      res.data.items.forEach(item => {
        item.creditEnhancementRanking = JSON.parse(item.creditEnhancementRanking)
        item.assetSecuritizationName = item.assetSecuritizationName
      })
      pagination.total = res.data.TotalCount;
      caseList.value = res.data.items //还有个分页
    } else {
      ElMessage.error(res.msg)
    }
  }
  function handleSizeChange() {
    getReport()
  }


  function handleCurrentChange() {
    getReport()
  }
  //切换项目获取增级列表 + 制定方案列表
  async function filterProject(a) {
    createData.assetSecuritizationName = a.assetSecuritizationName
    filterAssetTransferId.value = a.assetTransferId
    const data = qs.stringify({
      projectProposalId: filterSelectId.value
    })

    //获取发起日期
    let resStartData = await GetSettlementTime(qs.stringify({
      assetPoolId: a.assetPoolId
    }))
    if (resStartData.success) {
      createData.initialStartDate = resStartData.data.substring(0, 10)
    } else {
      ElMessage.warning(resStartData.msg)
    }
    //期限
    let res = await GetProductTerm(data)
    if (res.success) {
      // const currentDate = new Date();
      // const year = currentDate.getFullYear();
      // const month = String(currentDate.getMonth() + 1).padStart(2, '0');
      // const day = String(currentDate.getDate()).padStart(2, '0');
      // createData.initialStartDate = year + '-' + month + '-' + day
      // const endDate = addDay(Number(res.data))
      const endDate = addDay(Number(res.data), createData.initialStartDate)
      const year1 = endDate.getFullYear();
      const month1 = String(endDate.getMonth() + 1).padStart(2, '0');
      const day1 = String(endDate.getDate()).padStart(2, '0');
      createData.legalFinalMaturityDate = year1 + '-' + month1 + '-' + day1
    } else {
      ElMessage.warning(res.msg)
    }
    //处理开始时间和结束时间
    const data1 = qs.stringify({
      assetTransferId: a.assetTransferId
    })
    //发行规模
    let res1 = await GetExcessCollateral(data1)
    if (res1.success) {
      createData.issuanceAmount = res1.data
    } else {
      ElMessage.warning('请先完成超额抵押增信方式')
    }
    //收益率
    let res2 = await GetInfoByAssetTransferId(data1)
    if (res2.success) {
      createData.interestRate = res2.data.expectedIssueRate
    } else {
      ElMessage.warning(res2.msg)
    }
    //获取资产池的融资金额
    let res3 = await AssetTransferGetSmallLoanCreditbalance(data1)
    if (res3.success) {
      createData.principalBalance = res3.data
    } else {
      ElMessage.warning(res3.msg)
    }
    let res4 = await GetSPVName(data1)
    if (res4.success) {
      createData.trusteeSpv = res4.data.spvCompanyName
    } else {
      ElMessage.warning(res4.msg)
    }
    let res5 = await GetPriorityHierarchy(data1)
    if (res5.success) {
      tableData.value = res5.data
      tableData.value.forEach(item => {
        item.issuanceMoney = (createData.issuanceAmount * (item.sizePercentage / 100)).toFixed(2)
        item.interestRate = createData.interestRate
      })
    } else {
      ElMessage.warning(res5.msg)
    }
  }

  function addDay(dayNumber, dateStr) {
    var date = dateStr ? new Date(dateStr) : new Date();
    var ms = dayNumber * (1000 * 60 * 60 * 24);
    var newDate = new Date(date.getTime() + ms);
    return newDate;
  }

  async function saveCase() {
    if (!filterSelectId.value) {
      ElMessage.warning('请先选择资产证券化项目')
      return
    }
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      assetTransferId: filterAssetTransferId.value,
      creditEnhancementRanking: JSON.stringify(tableData.value),
      issuancePercentage: '',
      individualIssue: '',
      issuanceAmount: createData.issuanceAmount,//总发行金额 
      initialStartDate: createData.initialStartDate,//项目的初始起始日期 
      legalFinalMaturityDate: createData.legalFinalMaturityDate,// 项目的法定最终到期日期 
      pooledCapitalBy: '金融有限公司的小额贷款债权',//资本贡献方的名称（例如，XXX 公司） 
      principalBalance: createData.principalBalance,// 资产池的本金余额 
      initiator: '金融公司',// 发起/服务机构：发起人名称。 
      trusteeSpv: createData.trusteeSpv,/// 受托机构：SPv企业资产证券化）
      interestRate: createData.interestRate,/// 发行利率 
      assetSecuritizationName: createData.assetSecuritizationName
    }

    let res = await SecurityCreditRatingCreate(data)
    if (res.success) {
      ElMessage.success(res.msg)
      cancelAddNew()
      getReport()
      showReport.value = true
    } else {
      ElMessage.error(res.msg)
    }
  }
  function cancelCreate() {
    filterSelectId.value = ''
  }

  function clickReport() {
    filterSelectId.value = ''
    showReport.value = true
  }

  function cancelAddNew() {
    newReportVisible.value = false
    filterSelectId.value = ''
  }

  async function showCaseDetail(item) {
    const data = qs.stringify({
      securityCreditRatingId: item.securityCreditRatingId
    })
    let res = await PredeterminedRating(data)
    if (res.success) {
      const gradeArr = ['A', 'AA', 'AAA', 'B', 'BB', 'BBB', 'C', 'CC', 'CCC']
      for (var i = 0; i < item.creditEnhancementRanking.length; i++) {
        const index = gradeArr.findIndex(item => item == res.data)// 根据索引获取对应的等级
        const resultIndex = index + i
        item.creditEnhancementRanking[i].preGrade = gradeArr[resultIndex]
      }
      var result = "";
      for (var i = 0; i < item.creditEnhancementRanking.length; i++) {
        result += `${item.creditEnhancementRanking[i].priorityName}资产支持证券的信用等级为${item.creditEnhancementRanking[i].preGrade};`;
      }
      resultStr.value = result

      detailData.value = item
      detailData.value.projectName = item.assetSecuritizationName
    } else {
      ElMessage.error(res.msg)
    }
    caseDialog.value = true
  }

  return {
    showReport,
    filterSelectId,
    tableData,
    caseDialog,
    caseList,
    createData,
    detailData,
    saveCase,
    clickReport,
    showCaseDetail,
    filterProject,
    filterDataList,
    resultStr,
    pagination,
    columns,
    newReportVisible,
    handleSizeChange,
    handleCurrentChange,
    cancelAddNew
  }
}